
import logging#导入日志模块
from datetime import datetime#导日期时间模块

class Logger:#定义一个写日志的类
    def get_log(self,level,msg):
        log = logging.getLogger("web自动化测试")
        log.setLevel('DEBUG')
        formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d行-日志信息:%(message)s')
        sh = logging.StreamHandler()
        sh.setLevel('DEBUG')
        sh.setFormatter(formatter)
        datetime1 = datetime.now().date()
        fh = logging.FileHandler('./test_results/logs/'+str(datetime1)+'web_robot.log',encoding='utf-8')
        fh.setLevel('DEBUG')
        fh.setFormatter(formatter)
        log.addHandler(sh)
        log.addHandler(fh)
        fh = logging.FileHandler('./test_results/logs/'+str(datetime1)+'web_robot.log',encoding='utf-8')
        fh.setLevel('DEBUG')
        fh.setFormatter(formatter)
        log.addHandler(sh)
        log.addHandler(fh)

        if level == "DEBUG":
            log.debug(msg)
        elif level == 'INFO':
            log.info(msg)    #将msg作为提示信息写入到日志中
        elif level == "WARNING":
            log.warning(msg)
        elif level == "ERROR":
            log.error(msg)

        log.removeHandler(sh)
        log.removeHandler(fh)

    def debug(self,msg):
        self.get_log('DEBUG',msg) #调用logging中的获取日志信息的函数,因为默认是获取level大于debug
                                  #此处调用自定义的函数,就可以获取指定等级及日志信息

    def info(self,msg):
        self.get_log('INFO',msg)

    def warning(self,msg):
        self.get_log('WARNING',msg)

    def error(self,msg):
        self.get_log('ERROR',msg)


if __name__ == '__main__':
    log = Logger()
    log.debug('debug')